package com.srmt.document.business.quote;

import com.srmt.document.api.ContentReader;
import com.srmt.document.api.ContentWriter;
import com.srmt.document.exception.CellException;
import com.srmt.document.exception.TableException;
import com.srmt.document.model.ColumnData;
import com.srmt.document.model.TableData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 报价明细表智能填充器
 *
 * <p>核心功能：
 * <ul>
 *   <li>自动识别表格中已有的供应商和轮次</li>
 *   <li>为新供应商动态添加列组（包含合并单元格表头）</li>
 *   <li>智能填充新一轮报价数据</li>
 *   <li>跳过非"自动填写"的单元格</li>
 * </ul>
 *
 * <h3>表格结构假设：</h3>
 * <pre>
 * | 报价期细 | 目标价 | A-供应商              | 框价幅度 | B-供应商              | ...
 * |          |        | 第一轮 | 第二轮 | ... |          | 第一轮 | 第二轮 | ... |
 * | 产品单价 |   100  | 自动填写| 自动填写|    |          | 自动填写| 自动填写|    |
 * </pre>
 *
 * @author SRMT Development Team
 * @since 1.0.0
 */
public class QuoteTablePopulator {

    private static final Logger logger = LoggerFactory.getLogger(QuoteTablePopulator.class);

    private final ContentReader contentReader;
    private final ContentWriter contentWriter;

    // 表格结构常量
    private static final int FIXED_COLUMNS = 2; // 固定列数：报价期细、目标价
    private static final int HEADER_ROW_SUPPLIER = 1; // 供应商名所在行（1-based）
    private static final int HEADER_ROW_ROUND = 2; // 轮次名所在行（1-based）
    private static final int DATA_START_ROW = 3; // 数据开始行（1-based）

    // 正则模式
    private static final Pattern ROUND_PATTERN = Pattern.compile("第(\\d+|一|二|三|四|五|六|七|八|九|十)轮");
    private static final Pattern SUPPLIER_PATTERN = Pattern.compile("-供应商");

    /**
     * 构造函数
     *
     * @param contentReader 内容读取器
     * @param contentWriter 内容写入器
     */
    public QuoteTablePopulator(ContentReader contentReader, ContentWriter contentWriter) {
        if (contentReader == null || contentWriter == null) {
            throw new IllegalArgumentException("ContentReader 和 ContentWriter 不能为null");
        }
        this.contentReader = contentReader;
        this.contentWriter = contentWriter;
    }

    /**
     * 填充报价数据到表格
     *
     * @param docId 文档ID
     * @param tableAnchor 表格锚点（默认："报价明细表"）
     * @param quoteDataList 报价数据列表
     * @throws TableException 表格操作异常
     * @throws CellException 单元格操作异常
     */
    public void populateQuoteTable(String docId, String tableAnchor, List<SupplierQuoteData> quoteDataList)
            throws TableException, CellException {

        logger.info("开始填充报价明细表，文档ID: {}, 锚点: {}", docId, tableAnchor);

        if (quoteDataList == null || quoteDataList.isEmpty()) {
            logger.warn("报价数据列表为空，无需填充");
            return;
        }

        // 1. 读取表格分析现有结构
        TableStructureInfo structureInfo = analyzeTableStructure(docId, tableAnchor);
        logger.info("表格结构分析完成：{}", structureInfo);

        // 2. 处理每个供应商的报价数据
        for (SupplierQuoteData quoteData : quoteDataList) {
            // 如果有新增行列，需要更新结构数据
            structureInfo = processSupplierQuote(docId, tableAnchor, structureInfo, quoteData);
        }

        logger.info("报价明细表填充完成");
    }

    /**
     * 处理单个供应商的报价数据
     *
     * @return
     */
    private TableStructureInfo processSupplierQuote(String docId, String tableAnchor,
                                                    TableStructureInfo structureInfo,
                                                    SupplierQuoteData quoteData)
            throws TableException, CellException {

        String supplierName = quoteData.getSupplierName();
        int round = quoteData.getRound();

        logger.info("处理供应商 {} 第 {} 轮报价", supplierName, round);

        // 检查供应商是否已存在
        SupplierColumnInfo supplierInfo = structureInfo.getSupplierInfo(supplierName);

        if (supplierInfo == null) {
            // 新供应商，需要添加列组
            logger.info("供应商 {} 不存在，添加新供应商列组", supplierName);
            addNewSupplierColumns(docId, tableAnchor, structureInfo, supplierName, round);

            // 重新分析表格结构
            structureInfo = analyzeTableStructure(docId, tableAnchor);
            supplierInfo = structureInfo.getSupplierInfo(supplierName);
        } else {
            // 已有供应商，检查轮次列是否存在
            if (!supplierInfo.hasRound(round)) {
                logger.info("供应商 {} 缺少第 {} 轮列，添加新轮次列", supplierName, round);
                addNewRoundColumn(docId, tableAnchor, structureInfo, supplierInfo, round);

                // 重新分析表格结构
                structureInfo = analyzeTableStructure(docId, tableAnchor);
                supplierInfo = structureInfo.getSupplierInfo(supplierName);
            }
        }

        // 填充报价数据
        fillQuoteData(docId, tableAnchor, supplierInfo, round, quoteData.getQuoteValues());
        return structureInfo;
    }

    /**
     * 分析表格结构
     */
    private TableStructureInfo analyzeTableStructure(String docId, String tableAnchor)
            throws TableException {

        // 读取整个表格
        TableData tableData = contentReader.readTableAfter(docId, tableAnchor);
        int totalCols = tableData.getColumnCount();
        int totalRows = tableData.getRowCount();

        logger.debug("表格总列数: {}, 总行数: {}", totalCols, totalRows);

        TableStructureInfo structureInfo = new TableStructureInfo();

        // 解析供应商信息（从第1行）
        for (int col = FIXED_COLUMNS + 1; col <= totalCols; col++) {
            try {
                String cellContent = contentReader.readCellContent(docId, tableAnchor,
                        HEADER_ROW_SUPPLIER, col);

                if (cellContent != null && !cellContent.trim().isEmpty()) {
                    Matcher matcher = SUPPLIER_PATTERN.matcher(cellContent);
                    if (matcher.find()) {
                        String supplierName = cellContent.trim();

                        // 检查是否是合并单元格（供应商名通常跨多列）
                        boolean isMerged = contentReader.isMergedCell(docId, tableAnchor,
                                HEADER_ROW_SUPPLIER, col);

                        if (isMerged) {
                            // 这是供应商列组的起始列
                            SupplierColumnInfo supplierInfo = new SupplierColumnInfo(supplierName, col);
                            structureInfo.addSupplier(supplierName, supplierInfo);

                            logger.debug("发现供应商: {} 起始列: {}", supplierName, col);

                            // 解析该供应商的轮次列
                            parseSupplierRounds(docId, tableAnchor, col, totalCols, supplierInfo);
                        }
                    }
                }
            } catch (CellException e) {
                logger.debug("读取单元格 [1,{}] 失败: {}", col, e.getMessage());
            }
        }

        return structureInfo;
    }

    /**
     * 解析供应商的轮次列
     */
    private void parseSupplierRounds(String docId, String tableAnchor, int startCol, int totalCols,
                                    SupplierColumnInfo supplierInfo)
            throws TableException {

        // 从起始列开始，查找轮次信息（第2行）
        for (int col = startCol; col <= totalCols; col++) {
            try {
                String roundText = contentReader.readCellContent(docId, tableAnchor,
                        HEADER_ROW_ROUND, col);

                if (roundText != null && !roundText.trim().isEmpty()) {
                    Matcher matcher = ROUND_PATTERN.matcher(roundText);
                    if (matcher.find()) {
                        int roundNumber = parseRoundNumber(matcher.group(1));
                        supplierInfo.addRoundColumn(roundNumber, col);
                        logger.debug("供应商 {} 第 {} 轮列号: {}", supplierInfo.getSupplierName(),
                                roundNumber, col);
                    } else if (roundText.contains("降价")) {
                        // 遇到"降价幅度"列，说明该供应商列组结束
                        break;
                    }
                } else {
                    // 检查是否到达下一个供应商或表格末尾
                    String supplierCell = contentReader.readCellContent(docId, tableAnchor,
                            HEADER_ROW_SUPPLIER, col);
                    if (supplierCell != null && SUPPLIER_PATTERN.matcher(supplierCell).find()) {
                        // 到达下一个供应商
                        break;
                    }
                }
            } catch (CellException e) {
                logger.debug("解析轮次列 {} 失败: {}", col, e.getMessage());
            }
        }
    }

    /**
     * 解析轮次数字
     */
    private int parseRoundNumber(String roundText) {
        // 处理阿拉伯数字
        try {
            return Integer.parseInt(roundText);
        } catch (NumberFormatException e) {
            // 处理中文数字
            Map<String, Integer> chineseNumbers = new HashMap<>();
            chineseNumbers.put("一", 1);
            chineseNumbers.put("二", 2);
            chineseNumbers.put("三", 3);
            chineseNumbers.put("四", 4);
            chineseNumbers.put("五", 5);
            chineseNumbers.put("六", 6);
            chineseNumbers.put("七", 7);
            chineseNumbers.put("八", 8);
            chineseNumbers.put("九", 9);
            chineseNumbers.put("十", 10);

            return chineseNumbers.getOrDefault(roundText, 1);
        }
    }

    /**
     * 为新供应商添加列组
     */
    private void addNewSupplierColumns(String docId, String tableAnchor,
                                      TableStructureInfo structureInfo,
                                      String supplierName, int maxRound)
            throws TableException, CellException {

        logger.info("为供应商 {} 添加列组，包含 {} 轮 + 框价幅度列", supplierName, maxRound);

        // 确定插入位置（表格最后一列之后）
        int totalCols = contentReader.getTableColumnCount(docId, tableAnchor);
        int insertAfterCol = totalCols - 1;

        // 创建新列数据（轮次列 + 框价幅度列）
        List<ColumnData> newColumns = new ArrayList<>();
        int totalRows = contentReader.getTableRowCount(docId, tableAnchor);

        // 为每一轮创建一列
        for (int round = 1; round <= maxRound; round++) {
            List<String> columnCells = new ArrayList<>();
            // 第1行：供应商名（仅第一列填充，其他为空，后续合并）
            columnCells.add(round == 1 ? supplierName : "");
            // 第2行：轮次名
            columnCells.add("第" + convertToChineseNumber(round) + "轮报价");
            // 数据行：自动填写占位符
            for (int row = DATA_START_ROW; row <= totalRows; row++) {
                columnCells.add(" ");
            }
            newColumns.add(new ColumnData(columnCells));
        }

        // 添加框价幅度列
        List<String> marginColumn = new ArrayList<>();
        marginColumn.add(""); // 第1行空（供应商名会合并过来）
        marginColumn.add("降价幅度"); // 第2行
        for (int row = DATA_START_ROW; row <= totalRows; row++) {
            marginColumn.add(""); // 数据行默认为空
        }
        newColumns.add(new ColumnData(marginColumn));

        // 添加列
        contentWriter.addTableColumnsAfter(docId, tableAnchor, newColumns, insertAfterCol);

        // 合并供应商名单元格（第1行，跨所有新添加的列）
        int startMergeCol = insertAfterCol + 1;
        int endMergeCol = insertAfterCol + maxRound + 1; // 包含降价幅度列
        contentWriter.mergeCells(docId, tableAnchor, HEADER_ROW_SUPPLIER, startMergeCol,
                HEADER_ROW_SUPPLIER, endMergeCol);

        logger.info("成功添加供应商 {} 的列组，列范围: {}-{}", supplierName, startMergeCol, endMergeCol);
    }

    /**
     * 为已有供应商添加新轮次列
     */
    private void addNewRoundColumn(String docId, String tableAnchor,
                                  TableStructureInfo structureInfo,
                                  SupplierColumnInfo supplierInfo, int round)
            throws TableException, CellException {

        logger.info("为供应商 {} 添加第 {} 轮列", supplierInfo.getSupplierName(), round);

        // 确定插入位置（在框价幅度列之前）
        int maxRound = supplierInfo.getMaxRound();
        int lastRoundCol = supplierInfo.getRoundColumn(maxRound);
        int insertAfterCol = lastRoundCol; // 在最后一轮之后插入

        // 创建新轮次列数据
        List<ColumnData> newColumns = new ArrayList<>();

        List<String> columnCells = new ArrayList<>();
        columnCells.add(""); // 第1行空（供应商名已合并）
        columnCells.add("第" + convertToChineseNumber(round) + "轮报价"); // 第2行
        for (int row = DATA_START_ROW; row <= 17; row++) {
            columnCells.add(" ");
        }
        newColumns.add(new ColumnData(columnCells));

        // 添加列
        contentWriter.addTableColumnsAfter(docId, tableAnchor, newColumns, insertAfterCol);

        logger.info("成功为供应商 {} 添加第 {} 轮列", supplierInfo.getSupplierName(), round);
    }

    /**
     * 填充报价数据
     */
    private void fillQuoteData(String docId, String tableAnchor,
                              SupplierColumnInfo supplierInfo, int round,
                              List<String> quoteValues)
            throws CellException {

        logger.info("填充供应商 {} 第 {} 轮数据，数据量: {}",
                        supplierInfo.getSupplierName(), round, quoteValues.size());

        Integer roundColumn = supplierInfo.getRoundColumn(round);
        if (roundColumn == null) {
            throw new CellException("未找到供应商 " + supplierInfo.getSupplierName() +
                    " 第 " + round + " 轮的列");
        }

        // 批量填充数据（从第3行开始）
        List<List<String>> cellData = new ArrayList<>();
        for (String value : quoteValues) {
            cellData.add(Collections.singletonList(value));
        }

        contentWriter.setCellsContent(docId, tableAnchor, DATA_START_ROW, roundColumn, cellData);

        logger.info("成功填充 {} 个单元格数据", quoteValues.size());
    }

    /**
     * 转换数字为中文数字
     */
    private String convertToChineseNumber(int number) {
        String[] chineseNumbers = {"", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};
        if (number <= 10) {
            return chineseNumbers[number];
        }
        return String.valueOf(number);
    }

    // ============ 内部数据结构 ============

    /**
     * 表格结构信息
     */
    private static class TableStructureInfo {
        private final Map<String, SupplierColumnInfo> supplierMap = new LinkedHashMap<>();

        public void addSupplier(String supplierName, SupplierColumnInfo info) {
            supplierMap.put(supplierName, info);
        }

        public SupplierColumnInfo getSupplierInfo(String supplierName) {
            return supplierMap.get(supplierName);
        }

        public Collection<SupplierColumnInfo> getAllSuppliers() {
            return supplierMap.values();
        }

        @Override
        public String toString() {
            return "TableStructureInfo{suppliers=" + supplierMap.keySet() + "}";
        }
    }

    /**
     * 供应商列信息
     */
    private static class SupplierColumnInfo {
        private final String supplierName;
        private final int startColumn;
        private final Map<Integer, Integer> roundColumns = new TreeMap<>(); // round -> column

        public SupplierColumnInfo(String supplierName, int startColumn) {
            this.supplierName = supplierName;
            this.startColumn = startColumn;
        }

        public String getSupplierName() {
            return supplierName;
        }

        public int getStartColumn() {
            return startColumn;
        }

        public void addRoundColumn(int round, int column) {
            roundColumns.put(round, column);
        }

        public Integer getRoundColumn(int round) {
            return roundColumns.get(round);
        }

        public boolean hasRound(int round) {
            return roundColumns.containsKey(round);
        }

        public int getMaxRound() {
            return roundColumns.isEmpty() ? 0 : Collections.max(roundColumns.keySet());
        }

        @Override
        public String toString() {
            return "SupplierColumnInfo{" +
                   "name='" + supplierName + '\'' +
                   ", startCol=" + startColumn +
                   ", rounds=" + roundColumns.keySet() +
                   '}';
        }
    }
}
